package com.xiannimei.web.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xiannimei.Constants;
import com.xiannimei.web.MemberProfile;


public class UserDetailsInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log = LoggerFactory.getLogger(UserDetailsInterceptor.class);

	private List<String> loginEntries = new ArrayList<String>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
		HttpSession session = request.getSession();
		
		MemberProfile userDetails = (MemberProfile) session.getAttribute(Constants.SESSION_USER_CONTEXT);

		if (null != userDetails || !needLogin(request.getServletPath())) {
			return true;
		} else {
			// 设置 最后访问的url,以便登录时跳转
			setLastestUrl(request);
			response.sendRedirect(request.getContextPath() + "/auth/login.htm");
			return false;
		}
	}

	/**
	 * 设置 最后访问的url,以便登录时跳转
	 * 
	 * @param request
	 */
	private void setLastestUrl(HttpServletRequest request){
		if (needLogin(request.getServletPath()) && !isJsonRequest(request)) {
			String queryString = request.getQueryString() == null ? "" : request.getQueryString();
			log.debug("Query String: {}", queryString);
			queryString = queryString.replaceAll("restatic=true", "").trim();
			String path = request.getServletPath() + (queryString.length() == 0 ? "" : "?" + queryString);
			log.debug("Request:{}", path);
			request.getSession().setAttribute(Constants.SESSION_LATEST_VIEW_URL, path);
		}
	}
	
	private boolean needLogin(String path){
		boolean res = true;
		for (int i = 0; i < loginEntries.size(); i++) {
			String loginEntry = loginEntries.get(i);
			if (loginEntry.equals(path) || (loginEntry.endsWith("/*") && path.startsWith(loginEntry.substring(0, loginEntry.length() - 1)))) {
				res = false;
				break;
			}
		}
		return res;
	}

	public void setLoginEntries(List<String> loginEntries){
		this.loginEntries = loginEntries;
	}

	private boolean isJsonRequest(HttpServletRequest request){
		return request.getServletPath().endsWith(".json");
	}
}
